package com.kanshu.ksgb.fastread.doudou.module.login.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.event.LoginEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ActivateService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ActivityMgr;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.module.login.bean.SSOLoginStatusBean;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者    wcy
 * 时间    2018/11/18 22:46
 * 文件    doudou
 * 描述
 */
public class SSOManager {
    private static final int MAX_MIN = 1;
    private static final int VALIDE_CHECK_MINS = MAX_MIN * 20 * 1000;
    private volatile static SSOManager sManager;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean mStart;
    private PersonCenterService mCenterService;
    private SSOManager() {
        mCenterService = RetrofitHelper.getInstance().createService(PersonCenterService.class);
        mTimer = new Timer("sso", true);
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                AndroidSchedulers.mainThread().scheduleDirect(() -> {
                    // 处于登录状态才去请求服务器 查询是否在线
                    if(MMKVUserManager.getInstance().isUserLogin()) {
                        mCenterService.changeSSOLogin().subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<SSOLoginStatusBean>() {

                            @Override
                            @SuppressLint("ApplySharedPref")
                            public void onResponse(BaseResult<SSOLoginStatusBean> result, SSOLoginStatusBean item, Disposable disposable) {
                                String token = MMKVUserManager.getInstance().getLoginToken();
                                if(result != null && result.result.status.code == 0){   //接口请求成功
                                    if(TextUtils.isEmpty(item.token) || !TextUtils.equals(item.token, token)){ //token为空 或者 token不一致 代表token过期  用户需要重新登录  按照用户退出登录处理
                                        //DownloadBookService.clearAll();
                                        MMKVDefaultManager.getInstance().setOfflineUserId(UserUtils.getUserId());
                                        ARouter.getInstance().navigation(ActivateService.class).clearQueue();
                                        MMKVUserManager.getInstance().setLoginState(Constants.LoginState.TYPE_NO_LOGIN);
                                        UserUtils.saveUserId(MMKVDefaultManager.getInstance().getDeviceUserId());
                                        LoginEvent event = new LoginEvent();
                                        EventBus.getDefault().post(event);
                                    }
                                    if (TextUtils.isEmpty(item.token)) {
                                        Log.d("SSOManager", "token过期，请重新登录");
                                        ToastUtil.showStaticMessage("数据升级完毕，请重新登录。");
                                    } else if(!TextUtils.equals(item.token, token)){   //token过期  用户需要重新登录
                                        if (ActivityMgr.getInstance().existPageByTag(ARouterConfig.PageTagParams.SSO_LOGIN_PAGE)) {
                                            return;
                                        }
                                        ARouterUtils.toActivity(ARouterConfig.SSO_LOGIN);
                                    }
                                }
                            }

                            @Override
                            public void onError(int code, String errDesc) {
                                super.onError(code, errDesc);
                            }
                        });
                    }
                });
            }
        };
    }
    public static SSOManager getInstance() {
        if (sManager == null) {
            synchronized (SSOManager.class) {
                if (sManager == null) {
                    sManager = new SSOManager();
                }
            }
        }
        return sManager;
    }

    public void start() {
        if (mStart) {
            return;
        }
        mTimer.schedule(mTimerTask, 1200, VALIDE_CHECK_MINS);
        mStart = true;
    }

    public void cancel() {
        mTimerTask.cancel();
        mTimer.cancel();
        mStart = false;
    }

}
